import { _decorator, Camera, Color, Component, find, instantiate, Label, Material, MeshRenderer, Node, Prefab } from 'cc';
import { PlaneLabel } from './PlaneLabel';
import ResManager from './ResManager';
const { ccclass, property } = _decorator;

@ccclass('Plane')
export class Plane extends Component {
    private labelNode:Node = null
    private camera:Camera = null
    private planeLabel:PlaneLabel =null;
    private material:Material = null;
    private color: Color = null;
    async start() {
        this.labelNode = this.node.getChildByName('labelNode')
        this.camera = find('Main Camera').getComponent(Camera)
        this.material = this.node.getComponent(MeshRenderer).materials[0]
        this.color = this.material.getProperty('mainColor') as Color

        let prefab = await ResManager.instance.loadAssetByUrl<Prefab>('prefab/planeLabel')
        let uiLabelNode = instantiate(prefab);
        find('Canvas/planeLabelLayout').addChild(uiLabelNode)
        this.planeLabel = uiLabelNode.getComponent(PlaneLabel)
        uiLabelNode.getComponent(Label).string = this.node.name;
       
    }

    update(deltaTime: number) {
        
    }

     lateUpdate(dt: number): void {
        this.syncUILabel()
    }

    syncUILabel(){
        var wPos = this.labelNode.getWorldPosition();
        var sPos = this.camera.worldToScreen(wPos)
        this.planeLabel?.showAt(sPos)
    }

     changeColor(){
        
        this.material.setProperty('mainColor', Color.RED)
    }
    revertColor(){
        this.material.setProperty('mainColor', this.color)
    }
}


